'use strict';

const conn = require('../../../server/libs/DB/meter/asycnPool').pool;
const _ = require('underscore');
let comm = require('../../../server/libs/SIM/simComm').send;


function getSimMessage() {
    conn.query('SELECT device_id,device_no,sim FROM device_file WHERE delete_sign = 1 AND sim IS NOT NULL ', function (err, row) {
        if (!err && row.length) {
            _.forEach(row, function (deviceMes) {
                let resDataObj = {
                    'iccid': deviceMes.sim
                };
                comm(resDataObj, function (err, res) {
                    if (err) {
                        console.log(err);
                    } else {
                        let simMessage = JSON.parse(res);
                        console.log(simMessage);
                        if (simMessage.status === 1) {
                            let simMessageData = simMessage.data;
                            let device_id = deviceMes.device_id;
                            let insertObj = {
                                card_status: simMessageData.card_status,
                                gprs_all: simMessageData.gprs_all,
                                iccid: simMessageData.iccid,
                                update_time: simMessageData.update_time,
                                cate_name: simMessageData.cate_name,
                                expire_time:simMessageData.expire_time||null,
                                activate_time: simMessageData.activate_time||null,
                                imsi: simMessageData.imsi,
                                msisdn: simMessageData.msisdn,
                                gprs_use:simMessageData.gprs_use,
                                sms_num: simMessageData.sms_num,
                                device_id:device_id
                            };
                            let insertSql = `INSERT INTO sim_msg SET ? ON DUPLICATE KEY UPDATE ?`;
                            conn.query(insertSql, [insertObj, insertObj], function (err) {
                                if (err) console.log(err);
                            });
                        }else{
                        }
                    }
                });
            })
        }
    })
}

module.exports = getSimMessage;
